package cn.hengzhu.main_manager.web.openAPi.openApiToInner;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import cn.hengzhu.main_manager.repository.dao.ManageCaseBoxMapper;
import cn.hengzhu.main_manager.repository.dao.ManageCaseMapper;
import cn.hengzhu.main_manager.repository.dao.MobileKeyMapper;
import cn.hengzhu.main_manager.repository.domain.ManageCase;
import cn.hengzhu.main_manager.repository.domain.ManageCaseBox;
import cn.hengzhu.main_manager.repository.domain.ManageCaseBoxExample;
import cn.hengzhu.main_manager.repository.domain.ManageCaseExample;
import cn.hengzhu.main_manager.repository.domain.MobileKey;
import cn.hengzhu.main_manager.repository.domain.MobileKeyExample;
import cn.hengzhu.main_manager.service.ManageCaseBoxService;
import cn.hengzhu.main_manager.service.MobileKeyService;
import cn.hengzhu.main_manager.utils.MessageUtil;

/**
 * @author liuCheng
 * @since 2018年11月29日 下午6:02:12 快递存物取物逻辑
 */

@Controller
@RequestMapping("/msm")
public class ShortMessageController {

	@Autowired
	private ManageCaseMapper manageCaseMapper;
	@Autowired
	private ManageCaseBoxMapper manageCaseboxMapper;
	@Autowired
	private MobileKeyService mobileKeyService;
	@Autowired
	private MobileKeyMapper mobileKeyMapper;
	@Autowired
	private ManageCaseBoxService manageCaseBoxService;

	@RequestMapping("/sendSms")
	@ResponseBody
	public Map<String, Object> sendSms(String phoneNumber, String caseNo, String expressNumber,Byte size) throws Exception {
		Map<String, Object> map = new HashMap<>();
		// 查询caseNo
		ManageCaseExample manageCaseExample = new ManageCaseExample();
		manageCaseExample.createCriteria().andCaseNoEqualTo(caseNo);
		List<ManageCase> ManageCaseList = manageCaseMapper.selectByExample(manageCaseExample);
		if (!ManageCaseList.isEmpty()) {
			// 查询空余的柜子
			ManageCaseBoxExample manageCaseBoxExample = new ManageCaseBoxExample();
			manageCaseBoxExample.createCriteria().andIsDelEqualTo((byte) 0).andSwitchStatusEqualTo((byte) 1)
					.andIsConnEqualTo((byte) 1).andUseStatusEqualTo((byte) 0).andCaseNoEqualTo(caseNo).andSizeEqualTo(size);
			List<ManageCaseBox> manageCaseBoxList = manageCaseboxMapper.selectByExample(manageCaseBoxExample);
			if (!manageCaseBoxList.isEmpty()) {
				ManageCaseBox manageCaseBox = manageCaseBoxList.get(0);
				String code = MessageUtil.getCode();
				String address = ManageCaseList.get(0).getPlace();
				if (StringUtils.isNotBlank(address)) {
					try {
						mobileKeyService.openBoxBySendAfter(manageCaseBox, code, phoneNumber, caseNo, expressNumber);
						MessageUtil.sendSms(phoneNumber, address, code);
						Integer doorNum = manageCaseBox.getDoorNum();
						map.put("doorNum", doorNum);
						map.put("returnCode", 200);
						map.put("message", "开启" + doorNum + "号门成功,请放入物品，并关好箱门");
						return map;
					} catch (Exception e) {
						map.put("returnCode", 500);
						map.put("message", "系统错误");
						return map;
					}
				} else {
					map.put("returnCode", 500);
					map.put("message", "请在后台填写快递柜位置！！！");
					return map;
				}
			} else {
				map.put("returnCode", 404);// 没有空闲的柜子了
				map.put("message", "没有空闲的柜子了");
				return map;
			}
		} else {
			map.put("returnCode", 500);// 系统错误
			map.put("message", "系统错误");
			return map;
		}
	}

	/**
	 * @author liuCheng
	 * @since 2018年12月19日 上午10:21:57
	 * @param phoneNumber
	 * @param code
	 * @return
	 * @throws Exception
	 *             取件
	 */
	@RequestMapping("/pickUp")
	@ResponseBody
	public Map<String, Object> pickUp(String phoneNumber, String code) throws Exception {
		Map<String, Object> map = new HashMap<>();
		MobileKeyExample mobileKeyExample = new MobileKeyExample();
		mobileKeyExample.createCriteria().andPhoneEqualTo(phoneNumber).andStatusNotEqualTo((byte) 0);

		List<MobileKey> mobileKeyList = mobileKeyMapper.selectByExample(mobileKeyExample);

		if (!mobileKeyList.isEmpty()) {
			Map<String, List<MobileKey>> codeMap = mobileKeyList.stream()
					.collect(Collectors.groupingBy(MobileKey::getCode));

			List<MobileKey> mobileKeyList2 = codeMap.get(code);
			if (null != mobileKeyList2 && mobileKeyList2.size() > 0) {
				MobileKey mobileKey = mobileKeyList2.get(0);
				Integer mobileKeyId = mobileKey.getId();
				Integer boxId = mobileKey.getBoxId();
				Byte status = mobileKey.getStatus();
				ManageCaseBox manageCaseBox = manageCaseboxMapper.selectByPrimaryKey(boxId);
				Integer doorNum = manageCaseBox.getDoorNum();
				if (Byte.valueOf("1").equals(status)) {
					try {
						mobileKeyService.openBoxByPickUp(mobileKey, manageCaseBox);
						map.put("returnCode", 200);
						map.put("doorNum", doorNum);
						map.put("message", "开启" + doorNum + "号门成功,请取走你的物品，并关好箱门");
					} catch (Exception e) {
						map.put("returnCode", 404);
						map.put("message", "开启失败，请重试！！！");
					}
				} else {
					// 被清理了的快递柜
					// 返回消息的同时，修改短信的状态为无效
					MobileKey record=new MobileKey();
					record.setStatus((byte) 0);
					record.setId(mobileKeyId);
					mobileKeyMapper.updateByPrimaryKeySelective(record);
					map.put("returnCode", 404);
					map.put("message", "管理员已经取走了你的快递，请联系管理员！");
				}
			} else {
				map.put("returnCode", 403);
				map.put("message", "验证码输入错误");
			}

		} else {
			map.put("returnCode", 404);// 没有找到
			map.put("message", "没有你的快递");
		}
		return map;
	}

	/**
	 * @author liuCheng
	 * @since 2018年12月19日 上午9:08:27
	 * @param caseNo
	 * @param doors
	 * @return
	 * @throws Exception
	 *             快递柜清柜
	 */
	@RequestMapping("/clearBox")
	@ResponseBody
	public Map<String, Object> clearBox(String caseNo, String doors) throws Exception {
		Map<String, Object> map = new HashMap<>();

		if (StringUtils.isNotBlank(doors)) {
			List<String> asList = Arrays.asList(doors.split(","));
			List<Integer> doorList = asList.stream().map(Integer::parseInt).collect(Collectors.toList());
			ManageCaseBoxExample manageCaseBoxExample = new ManageCaseBoxExample();
			manageCaseBoxExample.createCriteria().andCaseNoEqualTo(caseNo).andDoorNumIn(doorList)
					.andIsDelEqualTo((byte) 0).andUseStatusEqualTo((byte) 1);
			List<ManageCaseBox> manageCaseBoxList = manageCaseboxMapper.selectByExample(manageCaseBoxExample);
			List<Integer> boxIdList = manageCaseBoxList.stream()
					.collect(Collectors.mapping(ManageCaseBox::getId, Collectors.toList()));
			if (null != boxIdList && !boxIdList.isEmpty()) {
				try {
					String loginName = "线下管理员操作";
					manageCaseBoxService.clearBoxByExpress(boxIdList, loginName);
					map.put("code", 200);
					map.put("message", "清除成功！");

				} catch (Exception e) {
					map.put("code", 400);
					map.put("message", "清除失败，请重试！");
				}

			} else {
				map.put("code", 200);
				map.put("message", "清除成功！");
			}
		} else {
			map.put("code", 400);
			map.put("message", "请选择要清除的储物柜！");
		}
		return map;
	}

}
